const express = require('express')
const db = require('../../db/db')


const router = express.Router()

router.get('/user/register', (req, res) => {
    res.render('user/register')
})

router.post('/api/user/register', (req, res) => {
    var user = new db.User.Model({
        account: req.body.account,
        password: req.body.password,
        createTime: new Date(),
        ip: db.formatIP(req.ip)
    })
        .save()
        .then(() => {
            res.apiSuccess('注册用户成功！')
        })
        .catch(err => {
            if (db.isDuplicateIndexError(err)) {
                res.apiMessage('帐号已注册！')
            }
            else if (err && err.errors) {
                if (err.errors.account) {
                    res.apiMessage(err.errors.account.message)
                }
                else if (err.errors.password) {
                    res.apiMessage(err.errors.password.message)
                }
            }
            else {
                res.apiError(err)
            }
        })
})


module.exports = router